/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { Scene, error, director, Node } from 'cc';
import { asyncIO, EVENT_SWITCH_SCENE, event } from '../core';
import { SceneBase } from './scene-base';

const TAG = 'lcc/scene/scene-manager.ts';

/**
 * @zh
 * 场景快照
 */
export interface SceneSnapshot {
    /**
     * @zh
     * 场景名
     */
    name: string;

    /**
     * @zh
     * 参数列表
     */
    args: any;
}

/**
 * @zh
 * 场景管理器
 */
class SceneManager {
    /**
     * @zh
     * 单例对象
     */
    private static _instance: SceneManager = null!;

    /**
     * @zh
     * 获得单例对象
     */
    static get instance() {
        if (SceneManager._instance === null) {
            SceneManager._instance = new SceneManager();
        }
        return SceneManager._instance;
    }

    /**
     * @zh
     * 场景栈
     */
    private _sceneStack: SceneSnapshot[] = [];

    /**
     * @zh
     * 当前场景
     */
    private _currentScene: SceneBase = null!;

    /**
     * @zh
     * 构造函数
     */
    private constructor() {}

    /**
     * @zh
     * 检查当前场景<br/>
     * 搜索场景的[[SceneBase]]脚本组件，如果不存在就会在第一个子节点上挂载一个新的
     */
    private checkCurrentScene() {
        if (!this._currentScene) {
            let snode = director.getScene()!;
            let scene = snode.getComponentInChildren(SceneBase)!;
            if (!scene) {
                let node = snode.children[0] as unknown as Node;
                if (node) {
                    scene = node.addComponent(SceneBase);
                } else {
                    error(TAG, 'scene must has one node at least');
                }
            }
            scene.configScene(snode.name);
            this._currentScene = scene;
        }
    }

    /**
     * @zh
     * 获得当前场景
     */
    get currentScene(): SceneBase {
        this.checkCurrentScene();
        return this._currentScene;
    }

    /**
     * @zh
     * 切换场景
     *
     * @param sname - 场景名
     * @param sargs - 快照参数
     */
    switchScene(sname: string, ...sargs: any[]) {
        event.emit(EVENT_SWITCH_SCENE + sname);
        event.emit(EVENT_SWITCH_SCENE, sname);
        asyncIO.inc();
        director.loadScene(sname, (err: Error | null, snode?: Scene) => {
            asyncIO.dec();
            if (!err && snode) {
                let scene = snode.getComponentInChildren(SceneBase)!;
                if (!scene) {
                    let node = snode.children[0] as unknown as Node;
                    if (node) {
                        scene = node.addComponent(SceneBase);
                    } else {
                        error(TAG, 'scene must has one node at least');
                    }
                }
                scene.configScene(snode.name);
                this._currentScene = scene;
                scene.onSceneLoad(...sargs);
            } else {
                error(TAG, `scene ${sname} switch failure`);
            }
        });
    }

    /**
     * @zh
     * 获得场景栈
     */
    get sceneStack() {
        return this._sceneStack;
    }

    /**
     * @zh
     * 压入场景到栈
     *
     * @param sname - 场景名
     * @param sargs - 快照参数
     */
    pushScene(sname: string, ...sargs: any[]) {
        let curscene = this.currentScene;
        if (curscene) {
            this._sceneStack.push({ name: curscene.sceneName, args: curscene.onSaveScene() });
        }
        this.switchScene(sname, ...sargs);
    }

    /**
     * @zh
     * 弹出栈中的场景
     */
    popScene() {
        let scenep = this._sceneStack.pop();
        if (scenep) {
            if (scenep.args instanceof Array) {
                this.switchScene(scenep.name, ...scenep.args);
            } else {
                this.switchScene(scenep.name, scenep.args);
            }
        }
    }
}

/**
 * @zh
 * 场景管理器对象
 */
export const sceneMgr = SceneManager.instance;
